import type { Ref } from "vue";
import { onMounted, onUnmounted } from "vue"

// 点击指定元素组件意外的任意地方触发回调函数
const useClickOutside = (elementRef: Ref<HTMLElement | undefined>, callback: () => void) => {
    const handler = (e: MouseEvent) => {
        if (elementRef.value && e.target) {
            if (!elementRef.value.contains(e.target as HTMLElement)) {
                callback()
            }
        }
    }

    onMounted(() => {
        document.addEventListener('click', handler)
    })

    onUnmounted(() => {
        document.addEventListener('click', handler)
    })
}

export default useClickOutside